﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HttpService
{

    class ImageDecode
    {

        double headLenRate;
        double startRate;
        double driftRate;
        double reverseRate;
        int[] randomArray;
        public ImageDecode(double headLenRate, double startRate, double driftRate, double reverseRate, int[] randomArray)
        {
            this.headLenRate = headLenRate;
            this.startRate = startRate;
            this.driftRate = driftRate;
            this.reverseRate = reverseRate;
            this.randomArray = randomArray;
        }
        public byte[] Decode(byte[] data)
        {
            Console.WriteLine(DateTime.Now.Millisecond);
            long total = data.Length;
            long start = (long)Math.Round(total * startRate, MidpointRounding.AwayFromZero);

            long driftNum = (long)Math.Round(total * driftRate, MidpointRounding.AwayFromZero);
            long reverseNum = (long)Math.Round(total * reverseRate, MidpointRounding.AwayFromZero);
            byte[] imageData = new byte[data.Length];
            Buffer.BlockCopy(data, 0, imageData, 0, imageData.Length);
            //imageData[0] = 256;
            for (var i = start; i < data.Length; i++)
            {
                long unit = ((data[i] ^ reverseNum) - driftNum) % 256;
                imageData[i] = Convert.ToByte(unit > -1 ? unit : unit + 256);

            }
            int unitLen = (int)Math.Ceiling(total * headLenRate / randomArray.Length);
            byte[] result = new byte[data.Length];
            Buffer.BlockCopy(imageData, 0, result, 0, result.Length);
            for (int i = 0; i < this.randomArray.Length; i++)
            {
              int index=  Array.IndexOf(this.randomArray, i);
                int a=index * unitLen;
                int b=i*unitLen;
              Buffer.BlockCopy(imageData,a , result,b , unitLen);
            }
            Console.WriteLine(DateTime.Now.Millisecond);
            return result;
        }
    }
}
